﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Skybot.Extension
{
    /// <summary>
    /// jtt894协议扩展转换帮肋类
    /// </summary>
    public static class JTT894Extension
    {

        /// <summary>
        /// 将当前字符串转换成为"-"分开的BCD吗
        /// </summary>
        /// <param name="bytes"></param>
        public static string ToBcdString(this byte[] bytes)
        {
            return BitConverter.ToString(bytes);
        }

        /// <summary>
        /// 转换为BCD数据时间
        /// </summary>
        /// <param name="bcdBytes"></param>
        /// <param name="yearStart">默认以年开始</param>
        /// <returns></returns>
        public static string ToBcdTime(this byte[] bcdBytes, bool yearStart = true)
        {
            if (yearStart)
            {
                if (bcdBytes.Length < 3 && yearStart)
                {

                    throw new NotSupportedException("BCD数据长度不够");
                }
                //不带毫秒
                if(bcdBytes.Length==6)
                {
                    return BitConverter.ToString(bcdBytes.Take(3).ToArray()) + " " + string.Join(":",   bcdBytes.Skip(3).Take(3).Select(p=>p.ToString("X2") ));

                }
                //带毫秒
                if (bcdBytes.Length == 7)
                {
                    return BitConverter.ToString(bcdBytes.Take(3).ToArray()) + " " + string.Join(":",    bcdBytes.Skip(3).Take(3).Select(p=>p.ToString("X2"))   ) +"."+ bcdBytes[bcdBytes.Length-1].ToString("X2");

                }

                return BitConverter.ToString(bcdBytes.Take(3).ToArray()) + " " + string.Join(":", bcdBytes.Skip(3).Take(3).Select(p => p.ToString("X2")));



            }
            else
            {
                return string.Join(":", bcdBytes.Skip(3).Take(20));

            }

        }

        /// <summary>
        /// 将一个格式化好的 字符串转换成为DataTime  包含年月日 如 14-12-01 12:33:33
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public static DateTime  Bcd894TimeToDateTime(this byte[] bcdBytes)
        {
            return DateTime.Parse("20" + bcdBytes.ToBcdTime());
        }
        
        /// <summary>
        ///  将度转换成为真实数据,以度为单位的经度值除以10的6次方，精确到百万分之一度
        /// </summary>
        /// <param name="latLon">原始10的六次方度</param>
        /// <returns></returns>
        public static double ToLatLon (this uint latLon)
        {
            return latLon*0.000001;
        }
    }
}
